package com.xuxiang.cloud.study.javaagent;

import javassist.ClassPool;
import javassist.CtClass;

import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.security.ProtectionDomain;

public class MyTransformer implements ClassFileTransformer {

    final String classone_path = "com/xuxiang/cloud/study/javaagent/demo/ClassOne";
    final String classtwo_path = "com/xuxiang/cloud/study/javaagent/demo/ClassTwo";
    final String classmodify_path = "com/xuxiang/cloud/study/javaagent/ClassModify";



    public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {


        try {
            if (classtwo_path.equals(className)) {

                ClassPool classPool = ClassPool.getDefault();

                CtClass ctClass = classPool.get("com.xuxiang.study.javaagent.ClassModify");
                ctClass.setName("com.xuxiang.study.javaagent.demo.ClassTwo");
                ctClass.setSuperclass(classPool.get("com.xuxiang.study.javaagent.demo.ClassOne"));
                ctClass.getConstructors()[0].setBody("{}");
                ctClass.detach();
                return ctClass.toBytecode();
            }
        } catch (Exception e) {
            System.out.println("Failed");
            e.printStackTrace();

        }

        return new byte[0];
    }
}
